---
--- 限流控制
--- Created by E.T.
--- DateTime: 2018/11/12 17:41
---

require "kong.plugins.xhg-rate-limiting.limit.bucket_limit"
require "kong.plugins.xhg-rate-limiting.limit.conn_limit"
--local service = kong.service
--local request = kong.request
local log = kong.log
local _M = {}
local bucket_limit = BucketLimit:new()
local conn_limit = ConnLimit:new()
-- 异常捕获
function try(block)
    local main = block.main
    local catch = block.catch
    local finally = block.finally
    assert(main)
    -- try to call it
    local ok, errors = xpcall(main, debug.traceback)
    if not ok then
        -- run the catch function
        if catch then
            catch(errors)
        end
    end
    -- run the finally function
    if finally then
        finally(ok, errors)
    end
    -- ok?
    if ok then
        return errors
    end
end

local function do_limlt()
    --local route_by = kong.ctx.shared.config.route_by
    --if route_by == "" then
    --    conn_limit:conn_limit()
    --else
    --    bucket_limit:rate_limit()
    --end
    bucket_limit:rate_limit()
end

function _M.execute()
    ---------------------------限流控制--------------------------------------
    try {
        main = function()
            local ok, err = do_limlt()
        end,
        catch = function(errors)
            log.err("【限流】限流异常->", errors)
        end,
        finally = function(ok, errors)
        end,
    }
end

return _M